

-- Namespace
	local _,mod = ...


-- Constants
	local font = {mod.path..'media\\bavaria.ttf',16,'OUTLINEMONOCHROME'}
	
	local c_default = { r = 1, g = .45, b = .45 }
	local c_white = { r = 1, g = 1, b = 1 }


-- Static
	local active = {}


-- Region creation
	mod.regions['control'] = function()
		local base = mod:CreateFrame('Frame',nil,UIParent)
			base:SetFrameStrata('MEDIUM')
		
		local text = base:CreateFontString(nil,'OVERLAY')
			text:SetFont(unpack(font))
			text:SetJustifyH('RIGHT')
			base.text = text
		
		local function fadeout(elapsed)
			local self = base
			local min = self.min
			min = min + elapsed; self.min = min
			if min >= .5 then
				self:Finished()
			else
				self:SetAlpha(1-(min/.5))
			end
		end
		
		local function countdown()
			local self = base
			local endT = active[self.spid] or 0
			local now = GetTime()
			if endT - now < 0 then
				active[self.spid] = nil
				self.text:SetText(self.msg)
				mod:timer_unregister(countdown)
				mod:anim_register(fadeout)(0)
			else
				self.text:SetText(('%s: %d!'):format(self.msg,endT-now))
			end
		end
		
		base:Listen('message',function(self,text,spid,r,g,b)
			self.text:SetTextColor(r,g,b)
			self.msg = text
			self.spid = spid
			self.min = 0
			mod:timer_register(.2,true,countdown)(0)
		end)
		
		base:Listen('reset',function(self)
			self:SetAlpha(1)
			self.text:SetText('')
			self.msg = nil
			self.spid = nil
			self.min = nil
			mod:anim_unregister(fadeout)
		end)
		
		base:Listen('order',function(self,id)
			self.text:ClearAllPoints()
			self.text:SetPoint('CENTER',UIParent,'CENTER',0,32-((id-1)*16))
		end)
		
		return base
	end


-- Events: loss-of-control
	local current = {}
	
	local function LOSS_OF_CONTROL()
		local n = C_LossOfControl.GetNumEvents()
		if not n then return end
		
		local _,spid,text,icon,startT,_,endT,school,_,dtype
		
		for i = 1,n do
			_,spid,text,icon,startT,_,endT,school,_,dtype = C_LossOfControl.GetEventInfo(i)
			if spid and startT and endT then
				current[spid] = true
				
				endT = startT + endT
				
				if active[spid] then
					active[spid] = endT  -- We still need to update the time, incase it changes.
				else
					active[spid] = endT
					
					local color
					if school and school > 0 then
						color = COMBATLOG_DEFAULT_COLORS.schoolColoring[school] or c_white
					else
						color = c_default
					end
					
					mod:message('control',
						text,
						spid,
						color.r,color.g,color.b
					)  -- Only dispatch the message if it's new.
				end
			end
		end
		
		for spid in pairs(active) do
			-- We have no concrete way of knowing when an effect ends, so we pretty
			-- much brute-force it.
			if not current[spid] then
				active[spid] = nil
			end
		end
		
		wipe(current)
	end
	
	mod:event_register('LOSS_OF_CONTROL_ADDED',LOSS_OF_CONTROL)
	mod:event_register('LOSS_OF_CONTROL_UPDATE',LOSS_OF_CONTROL)
